package cs.ni;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Observer;
import java.util.logging.FileHandler;

/**
 * Listen to the network for receiving a file on the dedicated socket.<br>
 * When a request arrives, it starts a Thread 
 * downloadHandler and stores it in the downloadMap.
 * <p>
 * Package  cs.ni
 * Project ChatSystemG1 - INSA 4INFOA1 - 2013/2014
 * @author Julie DUMONS & Juste OUEDRAOGO
 */
public class FileReceiverServer implements Runnable {
	/**
	 * listening socket 
	 */
	private ServerSocket socket;
	/**
	 * mapping remote user with the downloading handler
	 * to keep track of the downloads (we assume there is one transfert per user at a time)
	 */
	private HashMap<InetAddress, Thread> downloadMap;
	/**
	 * observes the downloads
	 * get notified when download finishes
	 */
	Observer observer;


	/**
	 * Constructor of FileReceiverServer
	 * @param sock  socket that server listen
	 * @param obs entity observer  (get notified when download finishes)
	 */
	public FileReceiverServer(ServerSocket sock, Observer obs){
		socket = sock;
		downloadMap = new HashMap<InetAddress,Thread>();
		observer = obs;
	}
	@Override
	public void run() {
		while(!Thread.currentThread().isInterrupted()){
			try {
				Socket client = socket.accept();
				InetAddress remoteAddr = client.getInetAddress();
				FileReceiverHandler handler = new FileReceiverHandler(client);
				handler.addObserver(observer);
				Thread downloadHandler = new Thread(handler);
				//start the download handler
				downloadHandler.start();
				//add the download handler in the map
				downloadMap.put(remoteAddr, downloadHandler);

			} catch (IOException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}

		}

	}

}
